package com.star.oauth.controller;

import com.star.entity.Result;
import com.star.entity.StatusCode;
import com.star.oauth.service.AuthService;
import com.star.oauth.util.AuthToken;
import com.star.oauth.util.CookieUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/*
			  ________   ___   ___        ___   ________   ___   ___        ___
	 ________|\   __  \_|\  \_|\  \______|\  \_|\   __  \_|\  \_|\  \______|\  \_________
	 \       \ \  \_\ /_\ \  \\ \  \     \ \  \\ \  \_\ /_\ \  \\ \  \     \ \  \        \
	  \       \ \   __  \\ \  \\ \  \     \ \  \\ \   __  \\ \  \\ \  \     \ \  \        \
	   \       \ \  \_\  \\ \  \\ \  \____ \ \  \\ \  \_\  \\ \  \\ \  \____ \ \  \        \
	    \       \ \_______\\ \__\\ \_______\\ \__\\ \_______\\ \__\\ \_______\\ \__\        \
	     \       \|_______| \|__| \|_______| \|__| \|_______| \|__| \|_______| \|__|         \
	 	  \___________________________________________________________________________________\

*/
@Controller
@RequestMapping("/oauth")
public class AuthController {
    @Autowired
    private AuthService authService;
    @Value("${auth.clientId}")//客户端id
    private String clientId;
    @Value("${auth.clientSecret}")//客户端密码
    private String clientSecret;
    @Value("${auth.cookieDomain}")//cookie域名
    private String cookieDomain;
    @Value("${auth.cookieMaxAge}")//cookie存活时间 -1关闭浏览器失效
    private int cookieMaxAge;

    //设置参数不是必须传递的
    @RequestMapping("/toLogin")
    public String toLogin(@RequestParam(value = "FROM",required = false,defaultValue = "") String from, Model model) {
        model.addAttribute("from", from);
        return "login";
    }

    @ResponseBody
    @RequestMapping("/login")
    public Result login(String username, String password, HttpServletResponse response) {

        //检验参数
        if (StringUtils.isEmpty(username)) {
            throw new RuntimeException("请输入用户名");
        }
        if (StringUtils.isEmpty(password)) {
            throw new RuntimeException("请输入密码");
        }
        //申请令牌
        AuthToken authToken = authService.login(username, password, clientId, clientSecret);
        //将jti存入cookie中
        this.saveJtiRoCookie(authToken.getJti(), response);

        return new Result(true, StatusCode.OK,"登录成功",authToken.getJti());
    }

    /**
     * 将jti存入cookie
     * @param jti
     * @param response
     */
    private void saveJtiRoCookie(String jti, HttpServletResponse response) {
        CookieUtil.addCookie(response, cookieDomain, "/", "uid", jti, cookieMaxAge, false);
    }
}
